package com.qingxin.sys.smslib;

import java.util.Date;

import com.qingxin.park.entity.BatchProductsView;
import com.qingxin.sms.entity.SmsQuery;
import com.qingxin.sms.service.SmsQueryService;
import com.qingxin.sys.utils.DateUtil;
import com.qingxin.sys.utils.StringUtils;

public class SmsFactory {
	
	private static SmsQueryService smsQueryService;
	private static SmsServer smsServer;
	
	private static boolean running;
	
	public static boolean isRunning(){
		return running;
	}
	
	
	/**
	 * 启动短信服务
	 * @param smsQueryService
	 * @return
	 */
	public static boolean startServer(SmsQueryService smsQueryService){
		if(isRunning()){
			return true;
		}
		SmsFactory.smsQueryService = smsQueryService;
		
		try {
			SmsSetting setting = new SmsSetting();
			if(StringUtils.isNotEmpty(setting.getComPort())){
				smsServer = new SmsServer();
				smsServer.startServer(setting);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
		running = true;
		return true;
	}
	
	
	/**
	 * 停止短信服务
	 */
	public static void stopServer(){
		try {
			if(smsServer != null){
				smsServer.stopServer();
			}
			running = false;
			smsServer = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 发送短信-加入发送队列
	 * @param phone
	 * @param message
	 */
	public static void sendSms(String phone, String message){
		SmsOutDataDeque.push(new SmsData(phone, message));
	}
	
	
	/**
	 * 发送短信-实际发送
	 * @param smsData
	 * @return
	 */
	protected static boolean send(SmsData smsData){
		if(!isRunning()){
			return false;
		}
		try {
			return smsServer.send(smsData.getPhone(), smsData.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	
	/**
	 * 接收短信
	 * @param phone
	 * @param message
	 */
	protected static void onReceivedSms(String phone, String message){
		SmsInDataDeque.push(new SmsData(phone, message));
	}
	
	
	/**
	 * 接收短信处理
	 * @param smsData
	 */
	public static void receivedSmsHandler(SmsData smsData){
		String phone = smsData.getPhone();
		if(phone.startsWith("86")){
			phone = phone.substring(2);
		}
		String message = smsData.getMessage();
		if(!smsQueryService.verifyCode(message)){
			return;
		}
		
		BatchProductsView products = smsQueryService.getBatchProductsView(message);
		if(products == null){
			return;
		}
		
		String sendMessage = products.getPdtname()+"；产地："+products.getParkName()+"；生产日期："+DateUtil.fmtDate(products.getEndTime())+"；经高平市农产品质量追溯平台监督与检测";
		sendSms(phone, sendMessage);
		
		SmsQuery smsQuery = new SmsQuery(null, phone, message, new Date(smsData.getTime()), sendMessage, new Date(), 1);
		smsQueryService.add(smsQuery);
		
	}
	
}
